//
//  RelatedListViewController.m
//  安好
//
//  Created by lianchuang on 14/12/10.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "RelatedListViewController.h"
#import "RelatedListViewCell.h"
#import "RelatedQustionsViewController.h"
@interface RelatedListViewController ()

@end

@implementation RelatedListViewController
{
    NSInteger page;
    NSMutableArray *dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    page=0;
    NSArray *keyW=[self.keyword componentsSeparatedByString:@"|"];
    NSMutableString *string=[[NSMutableString alloc]init];
    for (int i=0;i<keyW.count;i++) {
        [string appendString:[keyW objectAtIndex:i]];
    }
    self.navigationItem.title=[NSString stringWithFormat:@"%@",string];
    UIBarButtonItem *backImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    backImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backImg;
    dataArray=[[NSMutableArray alloc] init];
    self.tableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64)];
    self.tableview.dataSource=self;
    self.tableview.delegate=self;
    self.tableview.hidden=YES;
    [self.tableview addFooterWithTarget:self action:@selector(loadAllCNList)];
    [self.view addSubview:self.tableview];
    [self loadAllCNList];
}
-(void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)loadAllCNList
{
    page=page+1;
    NSString * postURL = [NSString stringWithFormat:@"%@question/cn/",kBaseURL];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{
                                 @"platform": kPlatform,
                                 @"version":kVersion,
                                 @"page":[NSString stringWithFormat:@"%ld",page],
                                 @"keyword":self.keyword,
                                 };
    [manage POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.tableview footerEndRefreshing];
        self.tableview.hidden=NO;
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
        }else{
            if ([[responseObject valueForKey:@"data"] count]==0) {
                [self.tableview footerEndRefreshing];
            }else
            {
                for(NSDictionary *dic in [responseObject valueForKey:@"data"])
                {
                    [dataArray addObject:dic];
                }
            }
            [self.tableview reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.tableview footerEndRefreshing];
//        [self shouLabel:@"暂无数据"];
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier=@"listcell";
    RelatedListViewCell *cell=[tableView dequeueReusableCellWithIdentifier:indentifier];
    if (!cell) {
        if (kScreenWidth==414) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"RelatedListViewCell" owner:self options:nil] lastObject];

        }else if(kScreenWidth==320){
            cell=[[[NSBundle mainBundle]loadNibNamed:@"RelatedListViewCell" owner:self options:nil] firstObject];
        }else{
            cell=[[[NSBundle mainBundle]loadNibNamed:@"RelatedListViewCell" owner:self options:nil] objectAtIndex:1];

        }
    }
    NSDictionary *dic=[dataArray objectAtIndex:indexPath.row];
    
    cell.content.text=[[dic valueForKey:@"content"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
    
    
    NSArray *keyarray=[self.keyword componentsSeparatedByString:@"|"];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:cell.content.text];

    for (int i=0; i<keyarray.count; i++) {
        NSRange range=[cell.content.text rangeOfString:[keyarray objectAtIndex:i]];
        [str addAttribute:NSForegroundColorAttributeName value:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] range:range];
    }

    [self autosizeFontAndSize:cell.content withText:cell.content.text];


    
    NSString *total=[NSString stringWithFormat:@"%@",[dic valueForKey:@"jishu"]];
    if ([total isEqualToString:@"0"]) {
        cell.answerCount.text=@"无回复";
        cell.answerImage.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#ffbb5b"];
    }else
    {
        cell.answerCount.text=[NSString stringWithFormat:@"%@条回复",[dic valueForKey:@"jishu"]];
        cell.answerImage.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#60dec5"];
    }
    cell.answerCount.textColor=[UIColor whiteColor];
    [self autosizeFontAndSize:cell.answerCount withText:cell.answerCount.text];
    cell.answerCount.frame=CGRectMake(kScreenWidth==414?25: 20, cell.content.bottom+10, cell.answerCount.width, cell.answerCount.height);
    cell.answerImage.frame=CGRectMake(kScreenWidth==414?20:15, cell.content.bottom+8, cell.answerCount.width+10, cell.answerCount.height);
    cell.dateline.text=[dic valueForKey:@"dateline"];
    cell.dateline.frame=CGRectMake(cell.dateline.left, cell.content.bottom+10, cell.dateline.width, cell.dateline.height);
    cell.clock.frame=CGRectMake(cell.dateline.left-15, cell.dateline.top+1, cell.clock.width, cell.clock.height);
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RelatedListViewCell *cell=(RelatedListViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.dateline.bottom+10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic=[dataArray objectAtIndex:indexPath.row];
    RelatedQustionsViewController *relatedQ=[[RelatedQustionsViewController alloc]initWithNibName:@"RelatedQustionsViewController" bundle:[NSBundle mainBundle]];
    relatedQ.qid=[dic valueForKey:@"qid"];
    relatedQ.questionInfo=dic;
    [self.navigationController pushViewController:relatedQ animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
- (void)autosizeFontAndSize:(UILabel *)label withText:(NSString *)text
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
    label.font=[UIFont systemFontOfSize:(kScreenWidth==414?15:13)];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];//调整行间距
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    label.attributedText = attributedString;
    [label sizeToFit];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
